package com.dd.ent.car.ui.widget.webview;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import com.dd.ent.car.R;
import com.dd.ent.car.common.util.NetworkHelper;
import com.dd.ent.car.ui.empty.EmptyLayout;
import com.pp.ent.base.common.SafeHandlerDispatch;
import com.pp.ent.base.log.MLog;

public class CustomWebView extends FrameLayout {
    private static final String TAG = "CustomWebView";
    /**
     * 顶部加载进度条
     */
    public static final int TYPE_PROGRESS_BAR = 1;
    /**
     * 中间弹出旋转进度框
     */
    public static final int TYPE_PROGRESS_DIALOG = 2;
    /**
     * 整屏动画进度页面
     */
    public static final int Type_PROGRESS_PAGE = 3;

    private static final int WHAT_HIDE_LOADING = 1;

    private static final int WHAT_HIDE_ERROR = 2;

    private EmptyLayout mErrorView;//错误页面
    private ObservableWebView mWebView;
    private String from = "";
    private RefreshListener mRefreshListener;//点击刷新按钮监听
    private DefaultJsInterface mJsInterface;//默认JS对象
    private String mCurrPageUrl;

    private ViewVisibilityListener mErrorViewVisibilityListener;//ErrorView显示、隐藏监听
    private ViewVisibilityListener mProgressVisibilityListener;//Progress显示、隐藏监听

    private Handler mHandler = new SafeHandlerDispatch() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case WHAT_HIDE_LOADING:
                    break;
                case WHAT_HIDE_ERROR:
                    doHideErrorView();
                    break;
            }
        }
    };

    public CustomWebView(Context context) {
        super(context);
        initView(context);
    }

    public CustomWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public CustomWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context);
    }

    private void initView(Context context) {
        View rootView = LayoutInflater.from(context).inflate(R.layout.custom_webview_layout, this, true);
        mWebView = (ObservableWebView) rootView.findViewById(R.id.custom_webView);
        initWebView(mWebView);
    }

    private void initWebView(WebView webView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if ((getContext().getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
                WebView.setWebContentsDebuggingEnabled(true);
            }
        }
        WebSettings ws = webView.getSettings();
        ws.setUserAgentString(appendUserAgent(ws.getUserAgentString()));
        ws.setJavaScriptEnabled(true);
        ws.setDomStorageEnabled(true);
        ws.setDatabaseEnabled(true);
        String databasePath = getContext().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        ws.setDatabasePath(databasePath);
        ws.setLoadWithOverviewMode(true);
        // 提高渲染的优先级
        ws.setRenderPriority(WebSettings.RenderPriority.HIGH);// 把图片加载放在最后来加载渲染
        ws.setBlockNetworkImage(false); // 对 网络图片 加载的设置
        ws.setAppCacheEnabled(true);
        String cachePath = getContext().getApplicationContext().getCacheDir().getPath();
        ws.setAppCachePath(cachePath);
        ws.setDefaultTextEncodingName("GBK");// 不设置系统默认“latin”，给个gbk
        // 不支持页面缩放
        ws.setSupportZoom(false);
        ws.setBuiltInZoomControls(false);
        ws.setDisplayZoomControls(false);
        //这配置不能删，主要是为了解决手机设置超大字体后，页面显示会错乱，所以强制webview在展示页面时别使用大字体
        ws.setTextSize(WebSettings.TextSize.NORMAL);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {//设置H5视频可以自动播放
            ws.setMediaPlaybackRequiresUserGesture(false);
        }
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.getSettings().setUseWideViewPort(true);
        webView.setWebChromeClient(mWebChromeClient);
        webView.setWebViewClient(mWebViewClient);
        mJsInterface = new DefaultJsInterface(getContext(), this);
        webView.addJavascriptInterface(mJsInterface, BaseJsInterface.NAME);
    }

    private String appendUserAgent(String oldUserAgent) {
        StringBuilder sb = new StringBuilder(oldUserAgent);
        sb.append(" iThunder");
        return sb.toString();
    }

    public void showErrorView() {
        if (mHandler.hasMessages(WHAT_HIDE_ERROR)) {
            mHandler.removeMessages(WHAT_HIDE_ERROR);
        }
        if (!NetworkHelper.isNetworkAvailable(getContext())) {
            //mErrorView.setErrorType(ErrorView.TYPE_INVALID_NETWORK);
        }

        if (mErrorView.getVisibility() == VISIBLE) return;

        mErrorView.setVisibility(View.VISIBLE);
        if (mErrorViewVisibilityListener != null) {
            mErrorViewVisibilityListener.onVisibilityChange(true);
        }
    }

    public void hideErrorView() {
        if (mHandler.hasMessages(WHAT_HIDE_ERROR)) {
            mHandler.removeMessages(WHAT_HIDE_ERROR);
        }
        mHandler.sendEmptyMessageDelayed(WHAT_HIDE_ERROR, 500);
    }

    private void doHideErrorView() {
        if (mErrorView.getVisibility() != VISIBLE) return;
        mErrorView.setVisibility(View.GONE);
        if (mErrorViewVisibilityListener != null) {
            mErrorViewVisibilityListener.onVisibilityChange(false);
        }
    }

    public void hideLoadingView() {
        if (mHandler.hasMessages(WHAT_HIDE_LOADING)) {
            mHandler.removeMessages(WHAT_HIDE_LOADING);
        }
        mHandler.sendEmptyMessageDelayed(WHAT_HIDE_LOADING, 500);
    }


    public void destroy() {
        if (mJsInterface != null) {
            mJsInterface.clearInterceptors();
        }
        if (mWebView != null) {
            mWebView.stopLoading();
            ViewParent viewParent = mWebView.getParent();
            if (viewParent != null) {
                ((ViewGroup) viewParent).removeView(mWebView);
            }
            mWebView.destroy();
            mWebView = null;
        }
    }

    public void onResume() {
        if (mWebView != null) {
            mWebView.onResume();
        }
    }

    public void onPause() {
        if (mWebView != null) {
            mWebView.onPause();
        }
    }

    public String getUrl() {
        if (mWebView != null) {
            return mWebView.getUrl();
        }
        return "";
    }

    public void stopLoading() {
        if (mWebView != null) {
            mWebView.stopLoading();
        }
    }

    public WebSettings getSettings() {
        if (mWebView != null) {
            return mWebView.getSettings();
        }
        return null;
    }

    public void loadUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        if (mWebView == null) {
            return;
        }
        if (url.startsWith(BaseJsInterface.JS_PREFIX)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                String evalUrl = url.substring(BaseJsInterface.JS_PREFIX.length());
                if (TextUtils.isEmpty(evalUrl)) {
                    return;
                }
                mWebView.evaluateJavascript(evalUrl, null);
            } else {
                mWebView.loadUrl(url);
            }
        } else {
            hideErrorView();
            mWebView.loadUrl(url);
            mCurrPageUrl = url;
        }
    }

    public void setErrorViewVisibilityListener(ViewVisibilityListener listener) {
        this.mErrorViewVisibilityListener = listener;
    }

    public void setProgressVisibilityListener(ViewVisibilityListener listener) {
        this.mProgressVisibilityListener = listener;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public void setWebChromeClient(WebChromeClient chromeClient) {
        mWebChromeClient.setExternalChromeClient(chromeClient);
    }

    public void setWebViewClient(WebViewClient webViewClient) {
        mWebViewClient.setExternalWebViewClient(webViewClient);
    }

    public void setDownloadListener(DownloadListener listener) {
        if (mWebView != null) {
            mWebView.setDownloadListener(listener);
        }
    }

    public void addJsMessageInterceptor(JsMessageInterceptor interceptor) {
        if (interceptor == null) {
            return;
        }
        interceptor.setupParams(getContext(), this);
        mJsInterface.addInterceptor(interceptor);
    }

    public void setOnScrollChangedListener(final ObservableWebView.OnScrollChangedListener listener) {
        mWebView.setOnScrollChangedListener(listener);
    }

    public interface RefreshListener {
        void onRefreshClick();
    }

    public boolean canGoBack() {
        if (mWebView != null) {
            return mWebView.canGoBack();
        }
        return false;
    }

    public void goBack() {
        if (mWebView != null) {
            mWebView.goBack();
        }
    }

    public void setRefreshListener(RefreshListener listener) {
        this.mRefreshListener = listener;
    }

    private CustomWebChromeClient mWebChromeClient = new CustomWebChromeClient();

    private CustomWebViewClient mWebViewClient = new CustomWebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // 如下方案可在非微信内部WebView的H5页面中调出微信支付
            if (url.startsWith("weixin://wap/pay?")) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                getContext().startActivity(intent);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mCurrPageUrl = url;
            MLog.debug(TAG, "onPageStarted--url=" + url);
            view.getSettings().setBlockNetworkImage(true);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            MLog.debug(TAG, "onPageFinished--url=" + url);
            hideLoadingView();
            //webview加载错误页面时，会加载data:text/html,chromewebdata,作为Error页面展示的一个补充
            //因为有可能出现onReceiveError回调在onPageStart之前的情况
            if (!NetworkHelper.isNetworkAvailable(getContext()) || "data:text/html,chromewebdata".equalsIgnoreCase(url)) {
                showErrorView();
            }
            view.getSettings().setBlockNetworkImage(false);
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            MLog.debug(TAG, "onReceivedError--url=" + failingUrl);
            hideLoadingView();
            view.stopLoading();
            clearHtmlContent();
            if (!NetworkHelper.isNetworkAvailable(getContext())) {
               // mErrorView.setErrorType(ErrorView.TYPE_INVALID_NETWORK);
            } else {
                if (errorCode == 404) {
                   // mErrorView.setErrorType(ErrorView.TYPE_GONE);
                }
            }
            showErrorView();
        }
    };

    /**
     * 清空页面内容
     */
    public void clearHtmlContent() {
        if (mWebView != null) {
            mWebView.loadUrl("javascript:document.body.innerHTML=\"\";");
        }
    }

    public interface ViewVisibilityListener {
        void onVisibilityChange(boolean isShow);
    }
}
